﻿using Orchard.Environment.Extensions;
using Orchard.Localization;
using Orchard.MediaLibrary.Fields;
using Orchard.Tokens;
using System.Linq;

namespace Vitus.Utils.Providers.Tokens
{
    [OrchardFeature("Vitus.MediaLibraryTokens")]
    public class MediaLibraryPickerFieldTokenProvider : ITokenProvider
    {
        public MediaLibraryPickerFieldTokenProvider()
        {
            T = NullLocalizer.Instance;
        }

        public Localizer T { get; set; }

        public void Describe(DescribeContext context)
        {
            context.For("MediaLibraryPickerField", T("Media Library Picker Field"), T("Tokens for Media Library Picker Fields."))
                .Token("MediaUrls", T("Media URLs"), T("URLs of picked media items."), "Text")
                .Token("AltTexts", T("Alternative Texts"), T("Alternative texts of picked media items."), "Text")
                .Token("Titles", T("Titles"), T("Titles of picked media items."), "Text")
                .Token("Captions", T("Captions"), T("Captions of picked media items."), "Text")
                .Token("MimeTypes", T("MIME Types"), T("MIME types of picked media items."), "Text")
                ;
        }

        public void Evaluate(EvaluateContext context)
        {
            context.For<MediaLibraryPickerField>("MediaLibraryPickerField")
                .Token("MediaUrls", picker => string.Join(",", picker.MediaParts.Select(mp => mp.MediaUrl)))
                    .Chain("MediaUrls", "Text", picker => string.Join(",", picker.MediaParts.Select(mp => mp.MediaUrl)))
                .Token("AltTexts", picker => string.Join(",", picker.MediaParts.Select(mp => mp.AlternateText)))
                    .Chain("AltTexts", "Text", picker => string.Join(",", picker.MediaParts.Select(mp => mp.AlternateText)))
                .Token("Titles", picker => string.Join(",", picker.MediaParts.Select(mp => mp.Title)))
                    .Chain("Titles", "Text", picker => string.Join(",", picker.MediaParts.Select(mp => mp.Title)))
                .Token("Captions", picker => string.Join(",", picker.MediaParts.Select(mp => mp.Caption)))
                    .Chain("Captions", "Text", picker => string.Join(",", picker.MediaParts.Select(mp => mp.Caption)))
                .Token("MimeTypes", picker => string.Join(",", picker.MediaParts.Select(mp => mp.MimeType)))
                    .Chain("MimeTypes", "Text", picker => string.Join(",", picker.MediaParts.Select(mp => mp.MimeType)))
                ;
        }
    }
}